<template>
  <div v-loading="detailInfoShow">
    <div class="requestAdd" v-if="!selectionMaterialShow">
      <!-- 筛选按钮 -->
      <div class="search-button" v-if="!contactAddShow">
        <el-button v-if="pageType === 'check' && route.name === 'PaymentCheck'" class="btn save"
          @click="handleCheckBtn2(projectFormRef, 3, '同意')"><el-icon class="icon" color="#fff">
            <Tickets />
          </el-icon>同意</el-button>
        <el-button v-if="pageType === 'check' && route.name === 'PaymentCheck'" class="btn withdraw"
          @click="handleCheckBtn2(projectFormRef, 4, '拒绝')"><el-icon class="icon" color="#fff">
            <DocumentDelete />
          </el-icon>拒绝</el-button>

        <el-button v-if="pageType === 'check' && route.name === 'PaymentCheck'" class="btn withdraw"
          @click="handleCheckBtn2(projectFormRef, 6, '驳回')"><el-icon class="icon" color="#fff">
            <DocumentDelete />
          </el-icon>驳回</el-button>
        <el-button v-if="pageType !== 'detail' && pageType !== 'check'" class="btn submit"
          @click="handleAddSave(requestFormRef, 1)"><el-icon class="icon" color="#fff">
            <Tickets />
          </el-icon>{{ pageType == 'add' ? '添加' : '提交' }}</el-button>
        <el-button v-if="pageType !== 'detail' && pageType !== 'check'" class="btn save"
          @click="handleAddSave(requestFormRef, 0)"><el-icon class="icon" color="#fff">
            <Tickets />
          </el-icon>存为草稿</el-button>

          <el-button
        v-if="activeName == 'approval' && flowInfoList.length"
        @click="handleEvaluate()"
        class="btn save"
        ><el-icon class="icon" color="#fff"> <Comment /> </el-icon
        >评论</el-button
      >
          <el-button v-if="activeName == 'approval' && flowInfoList.length" @click="handlePrint()" v-print="prints" class="btn add"
        ><el-icon class="icon" color="#fff"> <Printer /> </el-icon
        >打印</el-button
      >
        <el-button class="btn direction" @click="handleBack"><el-icon class="icon" color="#606266">
            <Back />
          </el-icon>返回</el-button>
      </div>

   <el-tabs type="border-card" v-model="activeName">
    <el-tab-pane label="付款信息" name="info">
      <el-collapse v-model="activeNames">
        <el-form :model="requestForm" ref="requestFormRef" :rules="queryRules" label-width="120px" v-enterToNext
          :disabled="pageType === 'detail' || pageType === 'check'">
          <!-- 基础信息 -->
          <el-collapse-item name="1" v-if="!contactAddShow" class="transform-down">
            <template #title>
              <span class="circle"></span>
              <span class="collapse-title">{{
                pageType !== "detail" && pageType !== "check "
                ? pageType === "add"
                  ? "新增"
                  : "编辑"
                : ""
              }}付款申请信息</span>
            </template>
            <div class="request-info">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="付款编号：">
                    <el-input disabled v-model="requestForm.paymentApplyCode" placeholder="自动获取" clearable
                      class="search-input" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="关联合同：">
                    <el-autocomplete
                      ref="contractRef"
                      popper-class="autoclass"
                      v-model="requestForm.purchaseContractCode"
                      :fetch-suggestions="querySearch"
                      placeholder="请输入"
                      @select="handleContractSelect"
                      style="width: 268px"
                      clearable
                      @clear="openInfo"
                      placement="bottom-end"
                    >
                      <template #default="{ item }">
                        <div class="auto-top" style="display: flex">
                          <div class="auto-item">合同编号</div>
                          <div class="auto-item">合同名称</div>
                          <div class="auto-item">供应商</div>
                        </div>
                        <div style="display: flex; width: 380px">
                          <div
                            class="auto-item"
                            style="text-align: left"
                            :title="item.purchaseContractCode"
                          >
                            {{ item.purchaseContractCode }}
                          </div>
                          <div
                            class="auto-item"
                            style="text-align: left"
                            :title="item.purchaseContractName"
                          >
                            {{ item.purchaseContractName }}
                          </div>
                          <div
                            class="auto-item"
                            style="text-align: left"
                            :title="item.distributorName"
                          >
                            {{ item.distributorName }}
                          </div>
                        </div>
                      </template>
                    </el-autocomplete>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="申请日期：" prop="applicantDate">
                    <el-date-picker v-model="requestForm.applicantDate" format="YYYY/MM/DD" class="search-input"
                      value-format="YYYY-MM-DD" type="date" placeholder="请选择" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="申请人：" prop="applicantId">
                    <el-select v-model="requestForm.applicantId" placeholder="请选择" clearable class="search-input"
                      @change="handleUserChange">
                      <el-option v-for="dict in userList" :key="dict.userId" :label="dict.nickName"
                        :value="dict.userId" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="申请部门：">
                    <el-input disabled v-model="requestForm.deptName" placeholder="自动获取" clearable class="search-input" />
                  </el-form-item>
                </el-col>
                <!-- </el-row>
              <el-row :gutter="0"> -->
                <el-col :span="6">
                  <el-form-item label="付款方式：" prop="paymentMethod">
                    <el-select v-model="requestForm.paymentMethod" placeholder="请选择" clearable class="search-input">
                      <el-option v-for="dict in wayList" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="付款金额：" prop="paymentAmount">
                    <el-input type="Number" v-model="requestForm.paymentAmount" placeholder="请输入" clearable
                      class="search-input">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="用款用途：" prop="useFunds">
                    <el-input v-model="requestForm.useFunds" placeholder="请列举如定金，进度款百分比，尾款、全款等" clearable
                      class="search-input" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="备注：">
                    <el-input style="width: 100%" maxlength="2000" v-model="requestForm.applyRemarks" type="textarea"
                      placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="合同附件：" prop="suppFileInfoVos">
                    <Upload :fileList="requestForm.suppFileInfoVos" :isFull="true" :limit="10" :showButton="true"
                      @success="(result) => uploadSuccess(result)" @deleteFile="(result) => uploadRemove(result)"
                      :isCanDelete="pageType == 'detail' ? false : true" :disabled="pageType == 'detail'" />
                    <!-- accept=".jpg,.png" -->
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
          <!-- 基础信息 -->
          <el-collapse-item name="2" v-if="!contactAddShow" class="transform-down">
            <template #title>
              <span class="circle"></span>
              <span class="collapse-title">收款账户</span>
            </template>
            <div class="request-info">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="账户类型：" prop="accountType">
                    <el-select v-model="requestForm.accountType" placeholder="请选择" clearable class="search-input"
                      @change="handleType">
                      <el-option v-for="dict in accountTypeList" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="户名：" prop="accountName">
                    <el-input v-model="requestForm.accountName" placeholder="真实姓名或企业名称" clearable class="search-input"
                      :maxlength="20" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="账号：" prop="accountCode">
                    <el-input v-model="requestForm.accountCode" placeholder="收款方银行账号" clearable class="search-input"
                      :maxlength="20" />
                  </el-form-item>
                </el-col>
                <el-col :span="6" v-if="!requestForm.accountType">
                  <el-form-item label="银行：" prop="bankName">
                    <el-input v-model="requestForm.bankName" placeholder="请输入银行名称" clearable class="search-input" />
                  </el-form-item>
                </el-col>
                <el-col :span="6" v-if="!requestForm.accountType">
                  <el-form-item label="银行所在地区：" prop="city">
                    <el-select filterable style="width: 120px" v-model="requestForm.province" placeholder="请选择" clearable
                      class="search-input" @change="handleProvince('province')">
                      <el-option v-for="dict in provinceList" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                    <el-select filterable style="width: 120px; margin: 0 5px" v-model="requestForm.city" placeholder="请选择"
                      clearable class="search-input" @change="handleProvince('city')">
                      <el-option v-for="dict in cityList" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                    <!-- <el-select
                    filterable
                    style="width: 93px"
                    v-model="requestForm.area"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                  >
                    <el-option
                      v-for="dict in areaList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select> -->
                  </el-form-item>
                </el-col>
                <el-col :span="6" v-if="!requestForm.accountType">
                  <el-form-item label="银行支行：">
                    <el-input v-model="requestForm.subBankName" placeholder="请输入" clearable class="search-input" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="备注：">
                    <el-input maxlength="2000" v-model="requestForm.bankRemarks" placeholder="请输入" clearable class="search-input" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
        </el-form>

        <!-- 联系人列表 -->
        <el-collapse-item name="3" style="position: relative" :class="!contactAddShow ? 'transform-down' : ''"
          v-if="pageType === 'check' || pageType === 'detail'">
          <template #title>
            <span class="circle"></span>
            <span class="collapse-title">付款列表</span>
            <div v-if="pageType === 'check'" class="search-button button-position">
              <el-button class="btn add" @click.stop="handleContactAdd(contactFormRef)"><el-icon class="icon"
                  color="#fff">
                  <Plus />
                </el-icon>添加</el-button>
            </div>
          </template>
          <div class="contact-info">
            <!-- 表格数据 -->
            <el-table :data="requestForm.payRecordInfoRespVos" border :height="'100%'"
              :header-cell-style="{ 'text-align': 'center' }" show-summary sum-text="合计" :summary-method="getSummaries">
              <!-- 操作模式 -->
              <el-table-column label="操作" align="center" :show-overflow-tooltip="true" width="60px"
                v-if="pageType === 'check'">
                <template #default="{ row, $index }">
                  <div class="table-operate">
                    <img src="@/assets/icons/images/delete.png" class="table-icon" title="删除"
                      @click="handleOperate('delete', row, $index)" />
                  </div>
                </template></el-table-column>
              <el-table-column label="付款日期" prop="paymentDate" :show-overflow-tooltip="true" min-width="160" />
              <el-table-column label=" 经办人" prop="paymentUserName" :show-overflow-tooltip="true" min-width="160" />
              <el-table-column label="经办部门" prop="deptName" :show-overflow-tooltip="true" min-width="160" />
              <el-table-column label="实付金额（元）" prop="actualAmount" :show-overflow-tooltip="true" min-width="160">
                <template #default="{ row, $index }">
                  <el-input v-if="pageType === 'check'" type="Number" v-model="row.actualAmount" placeholder="请输入"
                    clearable class="search-input" />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-collapse-item>
      </el-collapse>


    </el-tab-pane>
      <el-tab-pane label="审批进度" name="approval">
       <template v-if="auditList.length" >
        <div class="contact-info" id="print-iframe" >
            <!-- 步骤栏 -->
            <div :class="!printFlag? 'steps-box' : 'steps-print-box '">
            <el-steps
              :class="flowInfoList.length>7 ? 'BigSteps' : 'SmallSteps'"
              :active="flowingStep"
              
              finish-status="success"
            >
              <el-step v-for="(item, index) in flowInfoList" :key="index">
                <template #title>
                  <span :title="item.name">
                    {{ item.name }}
                  </span>
                </template>
                <template #description>
                  <div>
                    <p class="ription">{{ item.auditDate }}</p>
                    <p class="ription">{{ item.auditEmp }}</p>
                  </div>
                </template>
              </el-step>
            </el-steps>
          </div>
            <!-- 表格数据 -->
            <el-table
              :data="auditList"
              border
              :height="'100%'"
              :header-cell-style="{ 'text-align': 'center' }"
              sum-text=""
            >
              <!-- 操作模式 -->
              <el-table-column label="流程节点" prop="name" min-width="120">
              </el-table-column>
              <el-table-column label="审核人" prop="createUserName" min-width="120">
              </el-table-column>
              <el-table-column label="审核时间" prop="createTime" min-width="120">
              </el-table-column>
              <el-table-column label="审核意见" prop="resultName" min-width="120">
              </el-table-column>
              <el-table-column label="审核备注" prop="remark" min-width="120">
              </el-table-column>
            </el-table>
          </div>
          <!-- 评论 -->
          <el-table
            style="margin-top: 60px"
            :data="evaluateList"
            border
            :height="'100%'"
            :header-cell-style="{ 'text-align': 'center' }"
            sum-text=""
          >
            <!-- 操作模式 -->
            <el-table-column label="评论内容" prop="content" min-width="500">
            </el-table-column>
            <el-table-column
              label="评论人"
              prop="createUserName"
              min-width="120"
            >
            </el-table-column>
            <el-table-column label="评论时间" prop="createTime" min-width="120">
            </el-table-column>
          </el-table>
       </template>
          <div v-else>
            暂无审核
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <SelectionMaterial ref="selectionMaterialRef" v-if="selectionMaterialShow"
      v-model:selectionMaterialShow="selectionMaterialShow" @submitChoose="handleSelectMaterial" />

    <el-dialog :title="title" v-model="auditDialogShow" width="600px" append-to-body>
      <el-form-item label="审核备注：" label-width="90">
        <el-input style="width: 100%" v-model="auditRemark" maxlength="2000" placeholder="" type="textarea" clearable />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="color: #fff;background-color: rgba(67, 207, 124, 1); " v-if="auditResult == 3"
            @click="saveCheck()" v-loading="loadingCheck">同意</el-button>
          <el-button style="color: #fff;background-color: rgba(245, 108, 108, 1); " v-if="auditResult == 4"
            @click="saveCheck()" v-loading="loadingCheck">拒绝</el-button>
          <el-button style="color: #fff;background-color:rgba(245, 108, 108, 1); " v-if="auditResult == 6"
            @click="saveCheck()" v-loading="loadingCheck"> 驳回</el-button>
          <el-button style="background-color: #fff; " @click="closeAudit()
            ">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :title="''"
      v-model="evaluateDialogShow"
      width="600px"
      append-to-body
    >
      <el-form-item label="评论内容：" label-width="90">
        <el-input
          style="width: 100%"
          v-model="evaluateInfo"
          placeholder=""
          type="textarea"
          rows="5"
          maxlength="500"
          clearable
        />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            @click="saveEvaluate()"
            >保存</el-button
          >

          <el-button style="background-color: #fff" @click="closeEvaluate()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Picture as IconPicture } from "@element-plus/icons-vue";
import useUserStore from "@/store/modules/user";
import SelectionMaterial from "./selectionMaterial";
import Upload from "@/components/Upload/index";
import { addEvaluateApi, getEvaluateListApi } from "@/api/pub.js";
import {
  getProvinceApi,
  getUserListApi,
  getDeptListApi,
  addCustomerApi,
  editCustomerApi,
  getCustomerDetailApi,
} from "@/api/information/customer";

import { getProjectListApi } from "@/api/sales/project";
import {
  addRequestApi,
  editRequestApi,
  getRequestDetailApi,
  getRequestTableApi,
} from "@/api/purchase/request";
import {
  getContractListApi,
  addPaymentApi,
  editPaymentApi,
  getPaymentDetailApi,
  checkPaymentApi,
  selectAuditList
} from "@/api/purchase/payment";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import { getSupplierListApi } from "@/api/information/supplier";
const route = useRoute();
const emit = defineEmits([
  // 客户新增组件显隐
  "requestDtlShow",
  // 更新客户新增组件显隐
  "update:requestDtlShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
  // 合同用印id
  contractId: {
    type: Number,
    default: null,
  },
  // 合同用印编号
  contractCode: {
    type: Number,
    default: null,
  },
});
const activeName = ref('info')
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 客户表单引用
const requestFormRef = ref();
// 联系人表单引用
const contactFormRef = ref();
// 联系人操作类型
const operateType = ref("");
// 新增联系人表单显隐
const contactAddShow = ref(false);
const loadingCheck = ref(false);

// 选择审核
const auditDialogShow = ref(false);
// 选择物料显隐
const selectionMaterialShow = ref(false);
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 下拉框引用
const refSelect = ref();
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 付款方式列表
const wayList = ref([]);
// 单位列表
const unitList = ref([]);
// 供应商列表
const suppliereList = ref([]);
// 账户类型
const accountTypeList = ref([]);
// 采购合同列表
const contractList = ref([]);

let auditList = ref([]);

// 评论
const evaluateDialogShow = ref(false);
// 评论内容
const evaluateInfo = ref("");
// 评论列表
const evaluateList = ref([]);

//审核进度数据
const flowInfoList = ref([]);
//当前进度
const flowingStep = ref(0);

// 客户表单数据模板
const requestFormTemplate = {
  accountCode: "", // 收款方银行账号
  accountName: "", // 银行开户名称
  accountType: 0, // 账户类型
  applicantDate: "", // 申请日期
  applicantId: null, // 申请人id
  applyRemarks: "", // 	付款申请备注
  area: null, // 区
  bankName: "", // 银行名称
  bankRemarks: "", // 银行备注
  city: null, // 市
  payRecordInfoRespVos: [], // 付款申请明细信息对象
  paymentAmount: null, // 付款金额
  paymentCheckStatus: null, // 付款申请审核状态
  paymentMethod: null, // 付款方式
  province: null, // 省
  purchaseContractId: null, // 关联采购合同id
  subBankName: "", // 银行支行名称
  suppFileInfoVos: [], // 合同附件
  type: 0, // 	按钮类型0：存为草稿；1；提交
  useFunds: "", // 用款用途
};
// 联系人表单数据模板
const contactFormTemplate = {
  actualAmount: null, // 实付金额
  paymentApplyId: null, // 	关联付款申请id
  paymentDate: "", // 	付款日期
  paymentId: null, //  付款id
  paymentUserId: null, //付款用户id
};
const data = reactive({
  // 客户表单
  requestForm: JSON.parse(JSON.stringify(requestFormTemplate)),
  // 联系人表单
  contactForm: JSON.parse(JSON.stringify(contactFormTemplate)),
  // 客户表单校验规则
  queryRules: {
    applicantDate: [
      { required: true, message: "请选择申请日期", trigger: "change" },
    ],
    applicantId: [
      { required: true, message: "请选择申请人", trigger: "change" },
    ],
    purchaseContractId: [
      { required: true, message: "请选择关联合同", trigger: "change" },
    ],
    paymentMethod: [
      { required: true, message: "请选择付款方式", trigger: "change" },
    ],
    paymentAmount: [
      { required: true, message: "请输入付款金额", trigger: "blur" },
    ],
    useFunds: [{ required: true, message: "请输入用款用途", trigger: "blur" }],
    suppFileInfoVos: [
      { required: true, message: "请上传合同附件", trigger: "change" },
    ],
    accountType: [
      { required: true, message: "请选择账户类型", trigger: "change" },
    ],
    accountName: [{ required: true, message: "请输入户名", trigger: "blur" }],
    accountName: [{ required: true, message: "请输入户名", trigger: "blur" }],
    accountCode: [{ required: true, message: "请输入账号", trigger: "blur" }],
    bankName: [{ required: true, message: "请输入银行", trigger: "blur" }],
    city: [
      { required: true, message: "请选择银行所在地区", trigger: "change" },
    ],
  },
  // 联系人表单校验规则
  queryContactRules: {
    materialName: [
      { required: true, message: "请输入物料名称", trigger: "blur" },
    ],
    factoryCode: [
      { required: true, message: "请输入出厂型号", trigger: "blur" },
    ],
    technologyParameter: [
      { required: true, message: "请输入技术参数", trigger: "blur" },
    ],
    materialUnit: [
      { required: true, message: "请选择单位", trigger: "change" },
    ],
    purchaseNumber: [
      { required: true, message: "请输入请购数量", trigger: "blur" },
    ],
  },
  // 所属行业列表
  industryList: [],
  // 用户列表
  userList: [],
  // 省列表
  provinceList: [],
  // 市列表
  cityList: [],
  // 区列表
  areaList: [],
  // 用户列表
  userList: [],
  auditRemark: "",
  auditResult: "",
  applyId: "",
});

const {
  requestForm,
  contactForm,
  queryRules,
  queryContactRules,
  industryList,
  provinceList,
  cityList,
  areaList,
  userList,
  auditRemark, auditResult, applyId
} = toRefs(data);

import print from "vue3-print-nb";

// 使用自定义指令
const vPrint = print;
const printFlag = ref(false);

let prints = {
  id: "print-iframe",
  popTitle: "配置页眉标题", // 打印配置页上方的标题
  extraHead: "", // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  previewTitle: "预览的标题", // 打印预览的标题
  previewPrintBtnLabel: "预览结束，开始打印", // 打印预览的标题下方的按钮文本，点击可进入打印
  zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
  previewBeforeOpenCallback() {
    console.log("正在加载预览窗口！");
  }, // 预览窗口打开之前的callback
  previewOpenCallback() {
    console.log("已经加载完预览窗口，预览打开了！");
  }, // 预览窗口打开时的callback
  // 开始打印之前的callback
  beforeOpenCallback() {
    
    console.log("开始打印之前！");
   
  },
  openCallback() {
    console.log("执行打印了！");
  }, // 调用打印时的callback
  closeCallback() {
    console.log("关闭了打印工具！");
    printFlag.value= false
  }, // 关闭打印的callback(无法区分确认or取消)
  clickMounted() {
    console.log("点击v-print绑定的按钮了！");
    
  },
  standard: "",
  extarCss: "",
};

const handlePrint = ()=>{
  printFlag.value = true
}

// 处理评论按钮点击
const handleEvaluate = () => {
  evaluateDialogShow.value = true;
};

// 保存评论
const saveEvaluate = async () => {
  if (!evaluateInfo.value) return ElMessage.info("请输入评论内容！");
  const data = {
    businessId: requestForm.value.paymentApplyId,
    content: evaluateInfo.value,
    modelType: 11,
  };
  const result = await addEvaluateApi(data);
  if (result.code === 200) {
    ElMessage.success(result.msg);
    evaluateDialogShow.value = false;
    evaluateInfo.value = "";
    getEvaluateList()
  }
};

// 关闭评论弹窗
const closeEvaluate = () => {
  evaluateDialogShow.value = false;
  evaluateInfo.value = "";
};

// 获取评价列表
const getEvaluateList = async () => {
  const data = {
    businessId: requestForm.value.paymentApplyId,
    modelType: 11,
  };
  const result = await getEvaluateListApi(data);
  evaluateList.value = result.data || []
};

const handleCheckBtn2 = (requestFormRef, type, title) => {

  auditRemark.value = "";
  if (type == 3) {
    auditRemark.value = "同意";
  }

  auditResult.value = type;
  applyId.value = requestForm.value.paymentApplyId,
    auditDialogShow.value = true;
  loadingCheck.value = false;

};

const saveCheck = async () => {


  if (auditRemark.value === null || auditRemark.value === "") {
    ElMessage.error("审核备注不能为空");
    return;
  }

  if (auditResult.value == 3) {
    let totalMoney = 0;
    requestForm.value.payRecordInfoRespVos.forEach((item) => {
      totalMoney = totalMoney + item.actualAmount * 1;
    });
    if (totalMoney > requestForm.value.paymentAmount) {
      ElMessage.error("付款金额不能大于申请付款总额");
      return false;
    }
  }



  try {
    loadingCheck.value = true;
    requestForm.value.paymentCheckStatus = auditResult.value;
    requestForm.value.auditRemark = auditRemark.value;
    const res = await checkPaymentApi(requestForm.value);
    auditDialogShow.value = false;
    //loadingCheck.value =false;
    if (res.code === 200) {
      ElMessage.success(res.msg);

    } else {
      ElMessage.error(res.msg);
      return;
    }
    loadingCheck.value = false;
  } catch (error) {

    loadingCheck.value = false;

    ElMessage.error(error);
  }



}

const closeAudit = () => {
  auditRemark.value = "";
  auditResult.value = "";
  applyId.value = "";
  auditDialogShow.value = false;
}

/**
 * @description: 保存
 * @param {Object} requestFormRef 客户表单引用
 */
const handleAddSave = async (requestFormRef, type) => {
  if (!requestFormRef) return;
  await requestFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          requestForm.value.type = type;
          let res;
          if (!requestForm.value.purchaseApplyId) {
            // 新增客户
            res = await addPaymentApi(requestForm.value);
          } else {
            // 编辑客户
            res = await editPaymentApi(requestForm.value);
          }
          if (res.code === 200) {
            emit("update:requestDtlShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => { });
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail" || props.pageType === "check") {
    emit("updateFollowAddShow", false);
    emit("update:requestDtlShow", false);
    requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:requestDtlShow", false);
        requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
      })
      .catch(() => { });
  }
};

/**
 * @description: 处理手动输入
 */
const handleHand = () => {
  contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
  contactFormRef.value.resetFields();
};

/**
 * @description: 处理选择物料
 */
const handleMaterial = () => {
  selectionMaterialShow.value = true;
};

/**
 * @description: 处理物料选择
 */
const handleSelectMaterial = (value) => {
  if (value) {
    selectionMaterialShow.value = false;
    contactForm.value.materialCode = value.materialCode;
    contactForm.value.materialName = value.materialName;
    contactForm.value.factoryCode = value.factoryCode;
    contactForm.value.technologyParameter = value.technologyParameter;
    contactForm.value.materialUnit = value.materialUnit;
    contactForm.value.materialUnitName = value.materialUnitName;
    contactForm.value.supplierName = value.distributorName;
    contactForm.value.supplierId = value.supplierId;
    contactForm.value.manufacturerId = value.manufacturerId;
    contactForm.value.manufactureName = value.manufactureName;
  } else {
    ElMessage.info("请选择物料");
  }
};

/**
 * @description:关联合同
 */
 const handleContractSelect = (value) => {
  requestForm.value.purchaseContractId = value.purchaseContractId;
};

const querySearch = (queryString, cb) => {
  let results = queryString
    ? contractList.value.filter(createFilter(queryString))
    : contractList.value;
  if (queryString == "null") {
    results = contractList.value;
  }
  cb(results);
};
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};


/**
 * @description: 处理审核状态相关按钮
 * @param {String} type  类型
 * @param {String} title 标题
 */
const handleCheckBtn = (contractFormRef, type, title) => {
  ElMessageBox.confirm(`确定${title}以上数据吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      if (type == 3) {
        let totalMoney = 0;
        requestForm.value.payRecordInfoRespVos.forEach((item) => {
          totalMoney = totalMoney + item.actualAmount * 1;
        });
        if (totalMoney > requestForm.value.paymentAmount) {
          ElMessage.error("付款金额不能大于申请付款总额");
        }
        return false;
      }
      requestForm.value.paymentCheckStatus = type;
      const res = await checkPaymentApi(requestForm.value);
      if (res.code === 200) {
        emit("update:requestDtlShow", false);
        emit("refreshList", false);
        ElMessage.success(res.msg);
        contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => { });
};

/**
 * @description: 处理类型选择
 * @param {Number} value 选择值
 */
const handleType = (value) => {
  requestForm.value.bankName = "";
  requestForm.value.subBankName = "";
  requestForm.value.province = null;
  requestForm.value.city = null;
};

/**
 * @description: 处理人员选择
 * @param {Number} value 选择值
 */
const handleUserChange = (value) => {
  if (value) {
    const selectUser = userList.value.find((item) => item.userId === value);
    if (selectUser) {
      requestForm.value.deptName = selectUser.dept.deptName;
    }
  } else {
    requestForm.value.deptName = "";
  }
};

/**
 * @description: 处理单位选择
 * @param {Number} value 选择值
 */
const handleUnitChange = (value) => {
  contactForm.value.materialUnitName =
    unitList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 预览照片
 * @param {String} img 图片地址
 */
const showImg = (img) => {
  let imgArr = [];
  imgArr.push(img);
  return imgArr;
};

/**
 * @description: 计算总价
 * @param {Number} value 选择值
 */
const handlePrice = (value) => {
  contactForm.value.allPrice =
    (contactForm.value.purchasePrice * contactForm.value.purchaseNumber).toFixed(2);
};

/**
 * @description: 新增、编辑联系人
 */
const handleContactAdd = async () => {
  var today = new Date();
  var year = today.getFullYear(); //获取年份
  var month = today.getMonth() + 1; //获取月份
  var day = today.getDate(); //获取日期
  let date = year + "-" + month + "-" + day;
  const userInfo = await useUserStore().getInfo();
  requestForm.value.payRecordInfoRespVos.push({
    actualAmount: null, // 实付金额
    paymentApplyId: null, // 	关联付款申请id
    paymentDate: date, // 	付款日期
    paymentId: null, //  付款id
    paymentUserName: userInfo.user.nickName, // 用户名称
    deptName: userInfo.user.dept.deptName, // 部门名称
    paymentUserId: useUserStore().id, //付款用户id
  });
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  requestForm.value.suppFileInfoVos.push({ ...response, businessType: 11 });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  requestForm.value.suppFileInfoVos.splice(index, 1);
}

/**
 * @description: 处理省市区操作
 * @param {String} type 类型
 */
const handleProvince = (type) => {
  switch (type) {
    case "province":
      cityList.value = [];
      areaList.value = [];
      requestForm.value.city = null;
      requestForm.value.area = null;
      getProvinceApi(requestForm.value.province).then((res) => {
        if (res.code === 200) {
          cityList.value = res.data;
        }
      });
      break;
    case "city":
      areaList.value = [];
      requestForm.value.area = null;
      getProvinceApi(requestForm.value.city).then((res) => {
        if (res.code === 200) {
          areaList.value = res.data;
        }
      });
      break;
  }
};

/**
 * @description: 处理联系人操作
 */
const handleContactOperate = () => {
  contactAddShow.value = true;
  operateType.value = "add";
  nextTick(() => {
    refInput.value.focus();
  });
};

/**
 * @description: 联系人返回
 */
const handleRequestBack = () => {
  contactAddShow.value = false;
  nextTick(() => {
    refSelect.value.focus();
  });
};

/**
 * @description: 处理合计
 */
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    // 只对amount这一列进行总计核算。
    if (column.property === "actualAmount") {
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        sums[index] = sums[index].toFixed(2); // 保留2位小数，解决小数列合计精度缺失的问题
        // sums[index] += "元";
      } else {
        sums[index] = "";
      }
    }
  });
  // if (props.pageType === "add" || props.pageType === "edit") {
  //   sums[8] = sums[6] * sums[7];
  //   sums[7] = "";
  // } else {
  //   sums[7] = sums[5] * sums[6];
  //   sums[6] = "";
  // }

  return sums;
};

/**
 * @description: 处理联系人表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (type === "edit") {
    tableIndex.value = tabIndex;
    contactForm.value = {
      ...JSON.parse(JSON.stringify(row)),
      suppFileInfoVos: JSON.parse(JSON.stringify(row)).suppFileInfoVos
        ? JSON.parse(JSON.stringify(row)).suppFileInfoVos
        : [],
    };
    contactForm.value.allPrice =
      (contactForm.value.purchasePrice * contactForm.value.purchaseNumber).toFixed(2);
    contactAddShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      refInput.value.focus(); // 聚焦
    });
  } else {
    requestForm.value.payRecordInfoRespVos.splice(tabIndex, 1);
  }
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  try {
    detailInfoShow.value = true;
    const res = await getPaymentDetailApi(id);
    if (res) {
      requestForm.value = {
        ...res,
        payRecordInfoRespVos: res.payApplyRecordInfoRespVos,
      };
      getEvaluateList()
      // 存在为null无法push场景 
      if (!requestForm.value.payRecordInfoRespVos) {
        requestForm.value.payRecordInfoRespVos = [];
      }
      if (!requestForm.value.suppFileInfoVos) {
        requestForm.value.suppFileInfoVos = [];
      }
      await getProvinceApi(requestForm.value.province).then((res) => {
        if (res.code === 200) {
          cityList.value = res.data;
        }
      });
      await getProvinceApi(requestForm.value.city).then((res) => {
        if (res.code === 200) {
          areaList.value = res.data;
        }
      });
      const resAudit = await selectAuditList(id);
       auditList.value = resAudit.data;
       if(resAudit.data.length){
        flowInfoList.value = resAudit.data[0].chartVo.flowList;
        flowingStep.value = resAudit.data[0].chartVo.flowingStep;
       }
    }
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 付款方式
  await getDictsApi("erp_payment_method").then((res) => {
    if (res.code === 200) {
      wayList.value = res.data;
    }
  });

  // 单位列表
  await getDictsApi("material_unit").then((res) => {
    if (res.code === 200) {
      unitList.value = res.data;
    }
  });

  // 账户类型
  await getDictsApi("erp_account_type").then((res) => {
    if (res.code === 200) {
      accountTypeList.value = res.data;
    }
  });

  // 供应商列表
  await getSupplierListApi().then((res) => {
    if (res.code === 200) {
      res.rows.forEach((item) => {
        item.value = item.supplierName;
      });
      suppliereList.value = res.rows;
    }
  });

  await getUserListApi({}).then((res) => {
    // if (res.code === 200) {
    //   userList.value = res.rows;
    // }
    if (res.length > 0) {
      userList.value = res;
    }
  });

  // 采购合同列表
  await getContractListApi({}, {}).then((res) => {
    if (res) {
      contractList.value = res;
    }
  });

  // 省
  await getProvinceApi(1).then((res) => {
    if (res.code === 200) {
      provinceList.value = res.data;
    }
  });

  // // 销售部门列表
  // await getDeptListApi().then((res) => {
  //   if (res.code === 200) {
  //     deptList.value = res.data;
  //     nextTick(() => {
  //       refSelect.value.focus(); // 聚焦
  //     });
  //   }
  // });
}

onMounted(() => {
  nextTick(() => {
    requestForm.value.purchaseContractId = props.contractId;
    requestForm.value.purchaseContractCode = props.contractCode;
  });
  getDicts();
  if (props.pageType === "add") {
    nextTick(() => {
      refSelect.value.focus();
    });
  }
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.requestAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;

  .request-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }

  .contact-info {
    padding-top: 20px;
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }

  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }

  .search-input {
    width: 268px;
    height: 34px;
  }

  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
  }
  .ription {
      color: #8f8f8f;
      line-height: 16px;
      font-size: 12px;
    }
    :deep(.el-step__head.is-success) {
      color: #3399ff;
      border-color: #3399ff;
      position: relative;
    }
    :deep(.el-step__title) {
      font-size: 16px;
      line-height: 38px;
      position: absolute;
      top: -38px;
      width: 140px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    :deep(.el-step__title.is-success) {
      color: #3399ff;
    }
}

.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
  background-color: #fff;
}

.auto-item {
  width: 125px;
  text-align: left;
  white-space: nowrap;
  /* 禁止换行 */
  overflow: hidden;
  /* 隐藏超出部分 */
  text-overflow: ellipsis;
  /* 使用省略号表示超出部分 */
}

.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px;
  /* 设置最大高度 */
  overflow-y: auto;
  /* 超出高度时显示滚动条 */
}
.el-table {
  border: var(--el-table-border);
}
</style>
